# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import logging
import subprocess
import sys

from tornado import gen
from tornado.ioloop import IOLoop


@gen.coroutine
def run(argv, log_file_name):
  PERIOD = datetime.timedelta(minutes=30, seconds=10)
  proc_list = []
  next_run_time = datetime.datetime.now()
  while True:
    running_proc_list = []
    for proc in proc_list:
      if proc.poll() is None:
        running_proc_list.append(proc)
      else:
        proc.wait(0)
    proc_list = running_proc_list

    now = datetime.datetime.now()
    if now >= next_run_time:
      logging.info('Run! log_file=%s argv=%s' % (log_file_name, str(argv)))
      proc = subprocess.Popen('./pyrunner coin/strategy/mm/bitfinex/pass_unhedge.py %s &>> %s' %
                              (' '.join(argv), log_file_name),
                              shell=True)
      proc_list.append(proc)
      next_run_time += PERIOD
    yield gen.sleep(10)


def main(argv):
  log_file_name = argv[1]
  ioloop = IOLoop.current()
  # Not using argv for now.
  ioloop.add_callback(run, [], log_file_name)
  ioloop.start()


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')
  sys.exit(main(sys.argv))
